package org.example.conrtoller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import jdk.internal.util.xml.impl.Input;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.example.DictionaryService;
import org.example.StudentService;
import org.example.domain.Student;
import org.example.pageParam.CommonData;
import org.example.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.lang.System.out;

@Controller
@RequestMapping("/student/")
public class StudentController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private DictionaryService dictionaryService;
    @RequestMapping("studentMainPage.html")
    public String mainPage(@RequestParam(value = "examSymbol",required = false) String examSymbol,Model model){
        if (examSymbol!=null && examSymbol.equals("examSymbol")){
            //表示是exam模块中需要学生模板  需要做一些处理
            model.addAttribute("examSymbol",examSymbol);
        }
        return "student/studentMainPage";
    }
    @RequestMapping("studentFileUploadTemplate.html")
    public String fileUploadTemplate(){
        return "student/studentFileUploadTemplate";
    }
    @ResponseBody
    @RequestMapping(value = "importAllSubmit",produces = {"text/html;charset=UTF-8"})
    public String importAllSubmit(MultipartFile file){
        StringBuilder stringBuilder = null;
        try {
            ExcelReader excelReader = ExcelUtil.getReader(file.getInputStream());
            stringBuilder = new StringBuilder();
            for(int i=1;i<excelReader.getSheetCount();i++){
                excelReader = excelReader.setSheet(i);
                String sheetName = excelReader.getSheet().getSheetName();
                excelReader.addHeaderAlias("学号","code");
                excelReader.addHeaderAlias("姓名","sname");
                List<Student> temp = excelReader.readAll(Student.class);
                String[] sheetNames = sheetName.split("-");
                for (int j = 0;j<temp.size();j++){
                    Student students = temp.get(j);
                    students.setGrade(Integer.parseInt(sheetNames[0]));
                    students.setMajor((sheetNames[1]));
                    students.setClass_no(sheetNames[2]);
                    students.setMnemonic_code(PinyinUtil.getPinyin(students.getSname(),""));
                    students.setPass(DigestUtil.md5Hex(CommonData.DEFAULT_PASS));
                }
                String result = studentService.saves(temp);
                stringBuilder.append(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
    //有问题  先放一下
    @RequestMapping("downloadTemplate.xlsx")
    public ResponseEntity<byte[]> downloadTemplate(){
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("downloadTemplate/studentDemo.xlsx");
        byte[] bytes = null;
        try {
            bytes = new byte[inputStream.available()];
            IOUtils.read(inputStream,bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HttpHeaders httpHeaders = new HttpHeaders();//这里是为了返回xlsx时 出现下载框 否则默认展示在页面中
        httpHeaders.add("content-disposition","attachment;filename=students.xlsx");
        httpHeaders.add("content-type","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //content-type中的headValue是在tomcat中web.xml中找到的
        return new ResponseEntity<byte[]>(bytes,httpHeaders,HttpStatus.OK);
    }

    @RequestMapping("query.html")
    public String query(@RequestParam Map<String,Object> map,Model model){
        if (map.get("page")==null){
            map.put("page", CommonData.PAGE);
        }
        map.put("count",CommonData.COUNT);
        PageVO pageVO = studentService.query(map);
        model.addAttribute("pageVO",pageVO);
        String examSymbol = (String) map.get("examSymbol");
        if (examSymbol!=null && examSymbol.equals("examSymbol")){
            model.addAttribute("examSymbol",examSymbol);
        }
        return "student/studentClassContentTemplate";
    }
    @RequestMapping("limitQuery.html")
    public String limitQuery(@RequestParam Map<String,Object> map,Model model){
        //这个方法是后面想起的  不想改前面的东西 代码冗余了
        map.put("count",CommonData.COUNT);
        map.put("page",Integer.parseInt((String) map.get("page")));
        PageVO pageVO = studentService.query(map);
        model.addAttribute("pageVO",pageVO);
        String examSymbol = (String) map.get("examSymbol");
        if (examSymbol!=null && examSymbol.equals("examSymbol")){
            model.addAttribute("examSymbol",examSymbol);
        }
        return "student/studentClassContentTemplate";
    }
    @RequestMapping("queryClassStudent.html")
    public String queryClassStudent(@RequestParam Map<String,String> map,Model model){
        model.addAttribute("students",studentService.queryClassStudent(map));
        return "student/studentContentTemplate";
    }
    @RequestMapping("addStudent.html")
    public String addStudent(String className,Model model){
        if(className!=null && className !=""){
            model.addAttribute("className",className.split("-"));
        }else{
            model.addAttribute("majors",dictionaryService.queryAllMajor());
        }
        return "student/addStudentTemplate";
    }
    @ResponseBody
    @RequestMapping("addStudent")
    public Boolean addStudent(Student student){
        return studentService.addStudent(student);
    }
    @RequestMapping("edit.html")
    public String edit(String code,Model model){
        model.addAttribute("student",studentService.editStudentByCode(code));
        model.addAttribute("studentMajor",dictionaryService.queryAllMajor());
        return "student/editStudentTemplate";
    }
    @ResponseBody
    @RequestMapping("editSave")
    public Boolean editSave(Student student){
        return studentService.editSave(student);
    }
    @ResponseBody
    @RequestMapping("deleteClass")
    public void deleteClass(String className){
        studentService.deleteClass(className);
    }
    @ResponseBody
    @RequestMapping("deleteClassStudent")
    public void deleteClassStudent(String studentInfo){
        studentService.deleteClassStudent(studentInfo);
    }
    @ResponseBody
    @RequestMapping("exportClassStudent")
    public void exportClassStudent(String classInfo, HttpServletResponse response){
        String[] tempClassInfo = classInfo.split(",");
        ExcelWriter excelWriter = ExcelUtil.getWriter(true);
        for (int i = 0;i<tempClassInfo.length;i++){
            String[] temp = tempClassInfo[i].split("-");
            Map<String,String> map = new HashMap<>();
            map.put("grade",temp[0]);
            map.put("major",temp[1]);
            map.put("class_no",temp[2]);
            List<Student> studentList = studentService.queryClassStudent(map);

            excelWriter.addHeaderAlias("code","学号");
            excelWriter.addHeaderAlias("sname","学生名字");
            excelWriter.addHeaderAlias("mnemonic_code","助记码");
            excelWriter.addHeaderAlias("grade","年级");
            excelWriter.addHeaderAlias("major","专业");
            excelWriter.addHeaderAlias("class_no","班级");
            excelWriter.addHeaderAlias("create_time","创建时间");
            excelWriter.addHeaderAlias("update_time","修改时间");
            excelWriter.setOnlyAlias(true);
            excelWriter.setSheet(temp[0]+"-"+temp[1]+"-"+temp[2]);
            excelWriter.write(studentList,true);
        }
        excelWriter.getWorkbook().removeSheetAt(0);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition","attachment;filename=allClass.xlsx");
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        excelWriter.flush(out, true);
        excelWriter.close();
        IoUtil.close(out);
    }
}
